<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true"> 添加角色 </el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbotttom' ,i1===0 ? 'bdtop':'' ,'vcenter' ]" v-for="(itme1,i1) in scope.row.children"
              :key="itme1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,itme1.id)">{{itme1.authName}}</el-tag>
                <i class="el-icon-caret-right"> </i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row :class="[i2===0 ? '' : 'bdtop' ,'']" v-for="(itme2,i2) in itme1.children" :key="itme2.id">
                  <el-col :span="6">
                    <el-tag closable @close="removeRightById(scope.row,itme2.id)" type="success">{{itme2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"> </i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in itme2.children" :key="item3.id" closable
                      @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑
            </el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRolesById(scope.row.id)">删除
            </el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 对话框 -->
    <!-- 对话框添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" label-width="100px">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"> </el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRule">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 对话框添加角色 -->

    <!-- 对话框添加修改角色 -->
    <el-dialog title="修改角色" :visible.sync="eidDialogVisible" width="50%" label-width="100px">
      <el-form :model="editForm" :rules="eidFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"> </el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eidDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRuleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 对话框添加修改角色 -->

  </div>
</template>

<script>
export default {

  data () {
    return {
      // 所有角色列表
      rolelist: [],
      roleId: '',
      setRightDialogVisible: false,
      rightslist: [],
      // 树形结构绑定规则
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      // 添加角色弹窗
      addDialogVisible: false,
      addForm: { roleName: '', roleDesc: '' },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
      },
      // 角色修改
      eidDialogVisible: false,
      editForm: {},
      eidFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
      },
    }
  },

  created () {
    this.getRoleList()
  },
  methods: {
    // 获取所有角色列表
    async getRoleList () {
      const { data: res } = await this.$http.get('roles');
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败');
      }
      this.rolelist = res.data
    },
    async removeRightById (role, rightId) {
      // 根据id删除标签
      const confirmReult = await this.$confirm('永久删除该角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmReult)
      if (confirmReult !== 'confirm') {
        return this.$message.info('已经取消删除');
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
      if (res.meta.status !== 200) return this.$message.error('删除失败');
      role.children = res.data
      this.$message.success('删除成功');
      console.log('确认删除')
    },
    // 展示分配权限的对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      console.log(this.roleId)
      // 获取所有权限地址
      const { data: res } = await this.$http.get('rights/tree');
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      // 把获取的权限数据保存在data中
      this.rightslist = res.data;
      this.getLeafKeys(role, this.defKeys);
      this.setRightDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys (node, arr) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClosed () {
      this.defKeys = [];
    },
    async allotRights () {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr });

      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.getRoleList()
      this.setRightDialogVisible = false
      return this.$message.success('分配权限成功');
    },
    // 添加角色
    addRule () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return '';
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败');
        }
        this.getRoleList();
        this.addDialogVisible = false;
        return this.$message.success('添加角色成功');
      });
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    // 显示修改角色功能
    async showEditDialog (id) {
      this.eidDialogVisible = true;
      // 显示角色信息
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error('查询数据失败')
      }
      this.editForm = res.data

      this.editDialogVisible = true
    },
    // 修改用户信息
    editRuleInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return ''
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error('修改角色失败')
        } else {
          this.$message.success('修改角色成功')
          setTimeout(() => {
            this.addDialogVisible = false
            this.getRoleList()
          }, 1000);
        }
      })
    },
    // 删除角色
    async removeRolesById (id) {
      const confirmReult = await this.$confirm('永久删除该角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmReult)
      if (confirmReult !== 'confirm') {
        return this.$message.info('已经取消删除');
      }
      const { data: res } = await this.$http.delete('roles/' + id);
      if (res.meta.status !== 200) return this.$message.error('删除失败');
      this.getRoleList()
      this.$message.success('删除成功');
      console.log('确认删除')
    }
  },

}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbotttom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
